const util = require('../../utils/util.js')
let p

Page({

	data: {
		staticDomain: util.config('staticDomain'),
		appId: '',
		appName: '',
		authInfo: [],
		loadingPanel: {
			tip: '加载中'
		},
		authing: false
	},

	temp: {
		appId: null
	},

	onLoad: function (params) {
		p = this
		const extData = util.globalData('extDataTemp') || {
			appId: 'm-0001'
		}
		if (!extData || !extData.appId || !/^[a-z]\-[0-9]{4}$/.test(extData.appId))
			util.error('非法的参数', '传入参数数据非法，即将返回首页', () => {
				wx.switchTab({
					url: '/pages/home/home',
				})
			})
		p.temp.appId = extData.appId
		p.setData({
			appId: p.temp.appId
		})
		util.userLogin({
			p,
			scene: 'other',
			complete: () => {
				p.loadAuthData({
					appId: p.temp.appId
				})
			},
			fail: (title, msg) => {
				wx.navigateBack({
					delta: 1
				})
				util.error(title, msg)
			},
			notBind: () => {
				util.modal('绑定提示', '只有登录和绑定身份后才能授权登录哦，即将跳转到主页绑定', () => {
					wx.switchTab({
						url: '/pages/home/home'
					})
				})
			}
		})
	},

	onUnload: () => {
		util.unloadPage('authLogin')
	},

	loadAuthData: ({ appId }) => {
		util.request({
			source: 'authLogin',
			method: 'get',
			uri: `sys/apps/${appId}/authInfo`,
			success: ({ appName, authInfo}) => {
				p.setData({
					appName,
					authInfo
				})
				util.hideLoadingPanel(p)
			},
			fail: (code, msg) => {
				util.hideLoadingPanel(p)
				util.error('加载失败', util.errorHandler(code, msg))
			}
		})
	},

	authLogin: () => {
		p.setData({
			authing: true
		})
		util.request({
			source: 'authLogin',
			method: 'post',
			uri: `user/login/auth/${p.temp.appId}`,
			success: (authData) => {
				console.log(authData)
				wx.navigateBackMiniProgram({
					extraData: authData,
					fail: (err) => {
						console.error(err)
						util.error('跳转失败', '无法返回被授权程序，请重启微信重试')
					}
				})
			},
			fail: (code, msg) => {
				p.setData({
					authing: false
				})
				util.error('授权失败', util.errorHandler(code, msg))
			}
		})
	}

})